package com.jc.service.chain;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.CommonStr;
import com.jc.common.util.HttpUtil;
import com.jc.common.util.JSONUtil;
import com.jc.common.util.MD5;
import com.jc.common.util.UUIDUtil;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.LogType;
import com.jc.framework.util.PropertyPlaceholder;
import com.jc.service.apilog.ApiLogService;

@Service
public class ChainServiceImpl implements ChainService {
	
	private final Logger LOGGER = LoggerFactory.getLogger(ChainServiceImpl.class);
	
	final String chain_url = (String)PropertyPlaceholder.getProperty("chain.url");
	final String chain_key = (String)PropertyPlaceholder.getProperty("chain.key");
	final String app_id = (String)PropertyPlaceholder.getProperty("chain.app_id");
	
	
	
	
	@Autowired
	ApiLogService apiLogService;
	
	
	

    public ChainResult transfer(String coin_name, String amount, String payer_address, String payee_address, String order_id, String remarks){
    	Map<String,Object> map = new HashMap<String,Object>();
    	String ret = null;
        try {
            //生成验证签名：start
            //把除签名外的其它参数设置到map
            map.put("app_id", app_id);
            //map.put("num_id", " ");
            map.put("coin_name", coin_name);
            map.put("amount", amount);
            map.put("payer_address", payer_address);
            map.put("payee_address", payee_address);
            map.put("order_id", order_id);
            map.put("remarks", remarks);
            map.put("nonce_str", UUIDUtil.getUUID());
            //得到排序后的参数字符串
            String sign = toString(map);
            //拼接好平台分配给第三方的密钥
            sign += "&key="+ chain_key;
            //进行MD5加密
            sign = MD5.passmd5(sign).toUpperCase();
            map.put("sign", sign);
            //生成验证签名：end
            ret = HttpUtil.post(chain_url + "/transfer", map);
            ChainResult chainRet = null;
            if(JSONUtil.isJson(ret)) {
            	chainRet = JSONObject.parseObject(ret, ChainResult.class);
            	if(chainRet == null) {
            		//记录日志
            		apiLogService.addApiLog(LogType.REQUEST_CHAIN_ORDER, JSONObject.toJSONString(map), Conclusion.FAIL,"返回的不JSON格式,或者为空", ret);
            		return chainRet;
            	}
            	if(StringUtils.equals(CommonStr.SUCCESS, chainRet.getReturn_code())) {
            		apiLogService.addApiLog(LogType.REQUEST_CHAIN_ORDER, JSONObject.toJSONString(map), Conclusion.OK, null, ret);
            		return chainRet;
            	}else {
            		apiLogService.addApiLog(LogType.REQUEST_CHAIN_ORDER, JSONObject.toJSONString(map), Conclusion.FAIL,null, ret);
            		return chainRet;
            	}
            }else {
            	apiLogService.addApiLog(LogType.REQUEST_CHAIN_ORDER, JSONObject.toJSONString(map), Conclusion.FAIL,"返回的不JSON格式,或者为空", ret);
            	chainRet = new ChainResult();
            	chainRet.setReturn_code("99999");
            	chainRet.setReturn_msg("返回值 : " + ret + "  为空或不是JSON格式 !");
            	return chainRet;
            }
        } catch (Exception e) {
        	apiLogService.addApiLog(LogType.REQUEST_CHAIN_ORDER, JSONObject.toJSONString(map), Conclusion.FAIL,"", ret);
        	LOGGER.error("请求VRT转账交易错误, 详细信息: {},{}",e.getMessage(),e);
        }
        return null;
    }
    
    
    
    
    public ChainResult queryBalance(String coin_name, String address){
    	
    	Map<String,Object> map = new HashMap<String,Object>();
    	ChainResult chainRet = null;
    	String ret = null;
    	
    	
        try {
            //生成验证签名：start
            //把除签名外的其它参数设置到map
            map.put("app_id", app_id);
            //map.put("num_id", num_id);
            map.put("coin_name", coin_name);
            map.put("address", address);
            map.put("nonce_str", UUIDUtil.getUUID());
            //得到排序后的参数字符串
            String sign = toString(map);
            //拼接好平台分配给第三方的密钥
            sign += "&key="+ chain_key;
            //进行MD5加密
            sign = MD5.passmd5(sign).toUpperCase();
            map.put("sign", sign);
            //生成验证签名：end
            ret = HttpUtil.post(chain_url + "/balance", map);
            if(StringUtils.isBlank(ret)) {
            	throw new BaseServiceException("请求区块链错误,区块链系统返回值为空");
            }
            
            
            if(JSONUtil.isJson(ret)) {
            	chainRet = JSONObject.parseObject(ret, ChainResult.class);
            	if(chainRet == null) {
            		//记录日志
            		apiLogService.addApiLog(LogType.REQUEST_CHAIN_QUERY, JSONObject.toJSONString(map), Conclusion.FAIL,"返回值为空", ret);
            		return chainRet;
            	}
            	if(StringUtils.equals(CommonStr.SUCCESS, chainRet.getReturn_code())) {
            		apiLogService.addApiLog(LogType.REQUEST_CHAIN_QUERY, JSONObject.toJSONString(map), Conclusion.OK, null, ret);
            		return chainRet;
            	}else {
            		apiLogService.addApiLog(LogType.REQUEST_CHAIN_QUERY, JSONObject.toJSONString(map), Conclusion.FAIL,null, ret);
            		return chainRet;
            	}
            }else {
            	apiLogService.addApiLog(LogType.REQUEST_CHAIN_QUERY, JSONObject.toJSONString(map), Conclusion.FAIL,"返回的不JSON格式,或者为空", ret);
            	chainRet = new ChainResult();
            	chainRet.setReturn_code("99999");
            	chainRet.setReturn_msg("返回值 : " + ret + "  为空或不是JSON格式 !");
            	return chainRet;
            }
        } catch (Exception e) {        	
        	if(e != null && StringUtils.isNotBlank(e.getMessage())) {
				String error = e.getMessage();
				if(e.getMessage().length() > 150) {
					error = StringUtils.substring(e.getMessage(), 0, 150);
				}
				apiLogService.addApiLog(LogType.REQUEST_CHAIN_QUERY, JSONObject.toJSONString(map), Conclusion.FAIL , error , ret);
			}
        	LOGGER.error("请求VRT转账交易错误, 详细信息: {},{}",e.getMessage(),e);
        }
        return null;
    }
    
    
    
    /**
     * 对Map的key进行排序，并返回拼接好的字符串
     * @param map
     * @return
     */
    public String toString(Map<String,Object> map){
        Collection<String> keyset = map.keySet();
        StringBuffer sb = new StringBuffer("");
        List<String> list = new ArrayList<String>(keyset);
        // 对key键值按字典升序排序
        Collections.sort(list);
        
        for (int i = 0; i < list.size(); i++) {
            
            if(i > 0 ){
                sb.append("&");
            }
            sb.append(list.get(i) +"="+map.get(list.get(i)));
        }
        return sb.toString();
    }
    
	
}
